<template>
    <div class="search-suggestion">
        <van-cell icon="search" @click="$emit('search',item)" v-for="(item,index) in suggestions" :key="index">
            <div slot="title" v-html="highlight(item)"></div>
        </van-cell>
    </div>
    <!-- 搜素结果匹配的文字 高亮显示  v-html-->
</template>

<script>
import { getSearchSuggestions } from "@/api/search";
import { debounce } from "lodash";
export default {
    name:'SearchSuggestion',
    props:{
        searchText:{
            type:String,
            required:true
        }
    },
    data(){
        return {
            suggestions:[]
        }
    },
    watch:{
        searchText:{
            handler:debounce(function (value){
                this.loadSearchSuggestion(value)
            },200),
            
            immediate:true,//该回调会在侦听开始之后立即调用
        }
    },
    methods:{
        // 获取搜索建议
        async loadSearchSuggestion(q){
            try {
                const { data } = await getSearchSuggestions(q)
                this.suggestions = data.data.options
            } catch (error) {
                this.$toast('获取失败')
            }
        },
        highlight(text){
            const highlightstr = `<span class="active">${this.searchText}</span>`
            // 如果需要根据数据变量动态创建正则表达式时  则手动 new RegExp
                // 参数1：匹配模式字符串，他会根据这个字符串创建正则
                // 参数2：匹配模式，要写到字符串中
            const reg = new RegExp(this.searchText,'gi') //gi 全局小写
            return text.replace(reg,highlightstr)
        }
    }
};
</script>

<style lang="less" scoped>
.search-suggestion{
    /deep/ span.active{
        color: #3296fa;
    }
}
</style>